﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebPortal.Models.EntityModels;
using WebPortal.Models.ViewModel;

namespace WebPortal.Controllers
{
    public class MainController : BaseController
    {
        //
        // GET: /Main

        public ActionResult Index()
        {
            var basket = new List<int>();
            var categories = (from cat in dbCategories.Categories select cat).ToList();
            var goods = (from good in dbGoods.Goods select good).ToList();
            if (this.IsRegistredUser)
                basket = (from b in dbBasket.Basket where b.UserID == User.UserID select b.GoodID).ToList();
            GoodsModelList list = GoodsModel.GetGoods(goods, categories, basket);
            return View(list);
        }

        public ActionResult Search()
        {
            GoodsModelList list = new GoodsModelList();
            try
            {
                var basket = new List<int>();
                int catID = Convert.ToInt32(Request["id"]);
                var categories = (from cat in dbCategories.Categories select cat).ToList();
                var goods = (from good in dbGoods.Goods where good.CategoryID == catID select good).ToList();
                if (this.IsRegistredUser)
                    basket = (from b in dbBasket.Basket where b.UserID == User.UserID select b.GoodID).ToList();
                list = GoodsModel.GetGoods(goods, categories, basket);
            }
            catch (Exception e)
            {
                //
            }
            return View(list);
        }

        public ActionResult CategorySearch()
        {
            GoodsModelList list = new GoodsModelList();
            try
            {
                String name = Request["query"].ToLower();
                ViewData["search"] = name;
                var categories = (from cat in dbCategories.Categories where cat.Name.ToLower().Contains(name) select cat).ToList();
                if (categories.Count > 0)
                {
                    List<int> catIDs = new List<int>();
                    var basket = new List<int>();
                    foreach (Categories cat in categories)
                        catIDs.Add(cat.CategoryID);
                    var goods = (from good in dbGoods.Goods where catIDs.Contains(good.CategoryID) select good).ToList();
                    if (this.IsRegistredUser)
                        basket = (from b in dbBasket.Basket where b.UserID == User.UserID select b.GoodID).ToList();
                    list = GoodsModel.GetGoods(goods, categories, basket);
                }
            }
            catch (Exception e)
            {
                //
            }
            return View(list);
        }

    }
}
